package com.lmx.persistence.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;
import com.lmx.common.constants.CommonConstants;
import com.lmx.persistence.service.common.BaseCrudServiceImpl;
import com.lmx.repoDomain.tmodel.Tenant;
import com.lmx.repoDomain.tmodel.TenantPrivilege;

@Service
public class TenantPrivilegeServiceImpl extends
		BaseCrudServiceImpl<TenantPrivilege> implements TenantPrivilegeService {

	@Override
	public void allocateSysPrivilege(Tenant tenant, Integer sysType) {
		this.deleteByTenantId(tenant.getId());
		String insertSql = "insert into tnb_tenant_privilege(privilege_id,tenant_id) "
				+ "(select id,?1 from t_s_function as fun where del_status=0 && "
				+ "(fun.functiontype=1 || fun.functiontype=0 || fun.functiontype=3) && fun.system_type=?2 )";
		super.em.createNativeQuery(insertSql).setParameter(1, tenant.getId())
				.setParameter(2, sysType).executeUpdate();
		List<TenantPrivilege> privileges = super.find("tenant", tenant);
		tenant.setPrivileges(privileges);
	}

	@Override
	public void deleteByTenantId(Long tenantId) {
		String deleteSql = "DELETE FROM tnb_tenant_privilege WHERE tenant_id = :id ";
		super.em.createNativeQuery(deleteSql).setParameter("id", tenantId)
				.executeUpdate();
	}

	@Override
	@Transactional(readOnly = true)
	public void addPrivileges(Tenant tenant) {
		if (tenant == null) {
			return;
		}
		Tenant tenant2 = new Tenant();
		BeanUtils.copyProperties(tenant, tenant2);
		Map<String, Object> param = Maps.newHashMap();
		param.put("tenant.id", tenant.getId());
		param.put("delStatus", CommonConstants.DEL_STATUS_NO_0);
		List<TenantPrivilege> privileges = super.find(param);
		for (TenantPrivilege tenantPrivilege : privileges) {
			tenantPrivilege.setTenant(tenant2);
			if (tenantPrivilege.getPrivilege() != null) {
				tenantPrivilege.getPrivilege().setTenant(tenant2);
				tenantPrivilege.getPrivilege().setChildren(null);
			}
		}
		tenant.setPrivileges(privileges);
	}

	@Override
	public List<TenantPrivilege> findInitTenantPrivilkeges(Long tenantId) {
		String queryStr = "from TenantPrivilege as tp where tp.tenant.id = :tenantId"
				+ " and ( tp.privilege.type=0 or tp.privilege.type=1 or tp.privilege.type=3)"
				+ " and delStatus=0";
		return super.em.createQuery(queryStr)
				.setParameter("tenantId", tenantId).getResultList();
	}
}
